﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Live;
using System.Windows.Navigation;
using System.Runtime.Serialization.Json;
using System.IO.IsolatedStorage;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Device.Location;

namespace WorkTime_pan
{
    public partial class SkyDriveBackup : PhoneApplicationPage
    {
        private static LiveConnectSession session = null;
        private LiveConnectClient client;

        IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream;
        string albumID = "";

        string fileID
        {
            get
            {
                return MainPage.GetValueOrDefault<string>("fileID", "");
            }
            set
            {
                if (MainPage.AddOrUpdateValue("fileID", value))
                {
                    MainPage.settings.Save();
                }
            }
        }

        public SkyDriveBackup()
        {
            InitializeComponent();
        }

        private void signInButton1_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
            {
                client = new LiveConnectClient(e.Session);
                session = e.Session;

                Buckup.Visibility = System.Windows.Visibility.Visible;
                Restore.Visibility = System.Windows.Visibility.Visible;
            }
            else if (e.Session == null || e.Status == LiveConnectSessionStatus.NotConnected)
            {
                Buckup.Visibility = System.Windows.Visibility.Collapsed;
                Restore.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        public class SkyDriveContent
        {
            public string Name { get; set; }
            public string ID { get; set; }
        }
        List<SkyDriveContent> ContentList = new List<SkyDriveContent>();

        private void CheckAlbum()
        {
            if (session == null)
            {
                MessageBox.Show("You must sign in first.");
            }
            else
            {
                LiveConnectClient client = new LiveConnectClient(session);
                client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(clientDataFetch_GetCompleted);
                client.GetAsync("/me/skydrive/files");
            }
        }

        void clientDataFetch_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                List<object> data = (List<object>)e.Result["data"];
                foreach (IDictionary<string, object> content in data)
                {
                    SkyDriveContent skyContent = new SkyDriveContent();
                    skyContent.Name = (string)content["name"];
                    if (skyContent.Name == "WorkTime")
                    {
                        albumID = (string)content["id"];
                    }
                    ContentList.Add(skyContent);
                }
                if (albumID == "") CreateAlbum();
                else UploadJournal();
            }
            else
            {
                MessageBox.Show("Error calling API: " + e.Error.ToString());
            }
        }

        private void CreateAlbum()
        {
            Dictionary<string, object> fileData = new Dictionary<string, object>();
            fileData.Add("name", "WorkTime");
            LiveConnectClient client = new LiveConnectClient(session);
            client.PostCompleted +=
                new EventHandler<LiveOperationCompletedEventArgs>(CreateAlbum_Completed);
            client.PostAsync("me/albums", fileData);

        }

        void CreateAlbum_Completed(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                JObject jObject = JObject.Parse(e.RawResult);
                albumID = (string)jObject["id"];
                UploadJournal();
            }
            else
            {
                MessageBox.Show("Error calling API: " + e.Error.ToString());
            }
        }

        public void UploadJournal()
        {
            LiveConnectClient uploadClient = new LiveConnectClient(session);
            uploadClient.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(uploadClient_UploadCompleted);
            stream = iso.OpenFile("journal.txt", System.IO.FileMode.OpenOrCreate);
            uploadClient.UploadAsync(albumID, "journal.txt", stream,OverwriteOption.Overwrite);
        }

        void uploadClient_UploadCompleted(object sender, LiveOperationCompletedEventArgs e)
        {
            stream.Close();
            if (e.Error == null)
            {
                JObject jObject = JObject.Parse(e.RawResult);
                fileID = (string)jObject["id"];
            }
            else
            {
                MessageBox.Show("Error calling API: " + e.Error.ToString());
            }
        }

        public void RestoreJornal()
        {
            LiveConnectClient uploadClient = new LiveConnectClient(session);

            uploadClient.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(GetUserPictureCallback);
            uploadClient.DownloadAsync(fileID + "/content");
        }

        void clientDataFetch_GetCompleted1(object sender, LiveOperationCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (fileID == "") { ; }
                else RestoreJornal();
            }
            else
            {
                MessageBox.Show("Error calling API: " + e.Error.ToString());
            }
        }

        private void GetUserPictureCallback(object sender, LiveDownloadCompletedEventArgs e)
        {
            Stream stream = e.Result;

            try
            {
                if (e.Error == null)
                {
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("journal.txt", FileMode.Create))
                        {
                            stream.CopyTo(fileStream);
                        }
                    }

                }
                else
                {
                    MessageBox.Show(e.Error.Message, "Windows Live Error", MessageBoxButton.OK);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SkyDrive Exception", MessageBoxButton.OK);
            }
        }

        private void Buckup_Click(object sender, RoutedEventArgs e)
        {
            CheckAlbum();
        }
        private void Restore_Click(object sender, RoutedEventArgs e)
        {
            LiveConnectClient client = new LiveConnectClient(session);
            client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(clientDataFetch_GetCompleted1);
            client.GetAsync("/me/skydrive/files/");
        }
    }
}